package org.example.jwt.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.example.jwt.entity.Admin;
import org.example.jwt.service.AdminService;
import org.example.jwt.utils.JWTUtils;
import org.example.jwt.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@RestController
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/admin/login")
    public Result login(String username, String password){

        Admin admin = adminService.getOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getUserName, username));
        if (Objects.isNull(admin)){
            return Result.error().setMsg("用户不存在");
        }
        if (!Objects.equals(admin.getUserPwd(),password)){
            return Result.error().setMsg("密码错误");
        }
        Map<String, Object> payload = new HashMap<>();
        payload.put("id",admin.getId());
        payload.put("username",admin.getUserName());
        return Result.ok().setMsg("登录成功").setData(JWTUtils.createToken(payload));

    }

    @GetMapping("/index")
    public String home(){
        return "这里是首页";
    }


    @GetMapping("/admin/main")
    public String main(){
        return "这里是后台管理首页";
    }

//    @GetMapping("/admin/home")
//    public Result home(String token){
//        try{
//            DecodedJWT jwt = JWTUtils.verify(token);
//            String username = jwt.getClaim("username").asString();
//            Integer id = jwt.getClaim("id").asInt();
//            Admin admin = new Admin();
//            admin.setId(id);
//            admin.setUserName(username);
//            return Result.ok().setMsg("token验证成功").setData(admin);
//        }catch (SignatureVerificationException e){
//            return Result.error().setMsg("token签名无效");
//        }catch (TokenExpiredException e){
//            return Result.error().setMsg("token过期");
//        }catch (AlgorithmMismatchException e){
//            return Result.error().setMsg("token算法不一致");
//        }catch (InvalidClaimException e){
//            return Result.error().setMsg("token被篡改");
//        }catch(Exception e){
//            return Result.error().setMsg("token无效");
//        }
//    }
}
